package com.neoCalf.neoGroup.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neoCalf.neoCommon.entity.ChatMessage;
import com.neoCalf.neoCommon.entity.GroupInfo;
import com.neoCalf.neoCommon.entity.Session;
import com.neoCalf.neoCommon.entity.UserContact;
import com.neoCalf.neoCommon.enums.*;
import com.neoCalf.neoCommon.exception.BusinessException;
import com.neoCalf.neoCommon.model.R;
import com.neoCalf.neoCommon.model.dto.GroupInfoDto;
import com.neoCalf.neoCommon.model.dto.SendMessageDto;
import com.neoCalf.neoCommon.model.vo.GroupInitData;
import com.neoCalf.neoCommon.model.vo.UpdateGroup;
import com.neoCalf.neoCommon.utils.DataTool;
import com.neoCalf.neoCommon.utils.Md5Util;
import com.neoCalf.neoCommon.utils.SendUtils;
import com.neoCalf.neoCommon.utils.SessionSeq;
import com.neoCalf.neoGroup.feigns.ChatServiceFeign;
import com.neoCalf.neoGroup.feigns.ContactServiceFeign;
import com.neoCalf.neoGroup.mapper.GroupInfoMapper;
import com.neoCalf.neoGroup.service.GroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @author 小牛
 * @version 1.0
 * @description TODO
 * @date 2025/4/19 15:30
 */
@Service("groupService")
public class GroupServiceImpl extends ServiceImpl<GroupInfoMapper, GroupInfo> implements GroupService {
    @Autowired
    private GroupInfoMapper groupInfoMapper;
    @Autowired
    private ContactServiceFeign contactServiceFeign;
    @Autowired
    private SendUtils sendUtils;
    @Autowired
    private ChatServiceFeign chatServiceFeign;
    @Autowired
    private SessionSeq sessionSeq;

    @Override
    public Long myGroupCount(String ownerId) {
        LambdaQueryWrapper<GroupInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GroupInfo::getGroupOwnerId, ownerId);
        return groupInfoMapper.selectCount(queryWrapper);
    }

    @Override
    public List<GroupInfo> loadMyGroup(String userId) {
        LambdaQueryWrapper<GroupInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GroupInfo::getGroupOwnerId, userId);
        queryWrapper.orderByDesc(GroupInfo::getCreateTime);
        return groupInfoMapper.selectList(queryWrapper);
    }

    /**
     * 查询群信息
     */
    @Override
    public GroupInfo getGroupInfo(String groupId) {
        LambdaQueryWrapper<GroupInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GroupInfo::getGroupId, groupId);
        GroupInfo groupInfo = groupInfoMapper.selectOne(queryWrapper);
        Long groupMemberCount = contactServiceFeign.findGroupMemberCount(groupId).getResult();
        groupInfo.setMemberCount(groupMemberCount);
        return groupInfo;
    }

    @Override
    public GroupInfoDto getGroupInfo4Chat(String groupId) {
        LambdaQueryWrapper<GroupInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GroupInfo::getGroupId, groupId);
        GroupInfo groupInfo = groupInfoMapper.selectOne(queryWrapper);
        Long groupMemberCount = contactServiceFeign.findGroupMemberCount(groupId).getResult();
        groupInfo.setMemberCount(groupMemberCount);
        List<UserContact> userContactList = contactServiceFeign.findGroupMember(groupId).getResult();
        GroupInfoDto groupInfoDto = new GroupInfoDto();
        groupInfoDto.setGroupInfo(groupInfo);
        groupInfoDto.setUserContactList(userContactList);
        return groupInfoDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createGroup(String userId, String groupId, String groupName, String groupNotice, Integer joinType, String url) {
        if (JoinTypeEnum.getByType(joinType) == null) {
            throw new BusinessException(ResultCode.CODE_10017);
        }
        GroupInfo groupId1 = query().eq("group_id", groupId).last("limit 1").one();
        if (groupId1 != null) {
            throw new BusinessException(ResultCode.CODE_10017, "群聊ID已存在");
        }
        Long Time = new Date().getTime();
        GroupInfo groupInfo = new GroupInfo();
        groupInfo.setGroupId(groupId);
        groupInfo.setGroupName(groupName);
        groupInfo.setGroupOwnerId(userId);
        groupInfo.setCreateTime(Time);
        groupInfo.setGroupNotice(groupNotice);
        groupInfo.setJoinType(joinType);
        groupInfo.setStatus(GroupStatusEnum.NORMAL.getType());
        groupInfo.setAvatar(url);
        int insert = groupInfoMapper.insert(groupInfo);
        DataTool.checkAffectRow(insert, "创建群聊失败");

        SendMessageDto<GroupInfo> sendMessageDto = new SendMessageDto<>();
        sendMessageDto.setExtendData(groupInfo);
        sendUtils.sendMessage(sendMessageDto);

        // 创建群聊成功后，将创建者加入群聊
        UserContact userContact = new UserContact();
        userContact.setUserId(userId);
        userContact.setContactId(groupInfo.getGroupId());
        userContact.setContactType(UserContactTypeEnum.GROUP.getType());
        userContact.setStatus(GroupStatusEnum.NORMAL.getType());
        userContact.setCreateTime(Time);
        userContact.setLastUpdateTime(Time);
        userContact.setContactName(groupName);
        userContact.setWelcomeMessage(MessageTypeEnum.GROUP_CREATE.getInitMessage());
        R<String> stringR = contactServiceFeign.addGroupContact(userContact);
        if (!stringR.getCode().equals(ResultCode.Success.getCode())) {
            throw new BusinessException(ResultCode.Fail, "创建群聊失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGroupInfo(String userId, String nickName, GroupInfo groupInfo) {
        LambdaUpdateWrapper<GroupInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(GroupInfo::getGroupId, groupInfo.getGroupId());
        updateWrapper.eq(GroupInfo::getGroupOwnerId, userId);
        updateWrapper.set(DataTool.isStrLegal(groupInfo.getGroupName()), GroupInfo::getGroupName, groupInfo.getGroupName());
        updateWrapper.set(DataTool.isStrLegal(groupInfo.getGroupNotice()), GroupInfo::getGroupNotice, groupInfo.getGroupNotice());
        updateWrapper.set(!DataTool.isNull(groupInfo.getJoinType()), GroupInfo::getJoinType, groupInfo.getJoinType());
        updateWrapper.set(DataTool.isStrLegal(groupInfo.getAvatar()), GroupInfo::getAvatar, groupInfo.getAvatar());
        int update = groupInfoMapper.update(groupInfo, updateWrapper);
        DataTool.checkAffectRow(update, "更新群聊信息失败");

        String sessionId = Md5Util.encodeByMd5(groupInfo.getGroupId());
        Session session = new Session(null, null, sessionId, groupInfo.getGroupName());
        chatServiceFeign.updateSession(session);

        // 发送群聊信息修改消息
        ChatMessage chatMessage = new ChatMessage(
                sessionSeq.next(sessionId),
                sessionId,
                MessageTypeEnum.GROUP_INFO_UPDATE.getType(),
                nickName + " 修改了群聊信息",
                userId,
                nickName,
                new Date().getTime(),
                groupInfo.getGroupId(),
                UserContactTypeEnum.GROUP.getType(),
                MessageStatusEnum.FLUSH.getStatus()
        );
        chatServiceFeign.addChatMessage(chatMessage);

        SendMessageDto<UpdateGroup> sendMessageDto = new SendMessageDto<>();
        UpdateGroup updateGroup = new UpdateGroup();
        updateGroup.setSession(session);
        updateGroup.setChatMessage(chatMessage);
        sendMessageDto.setExtendData(updateGroup);

        sendMessageDto.setContactId(groupInfo.getGroupId());
        sendMessageDto.setContactType(UserContactTypeEnum.GROUP.getType());
        sendMessageDto.setMessageType(MessageTypeEnum.GROUP_INFO_UPDATE.getType());
        sendUtils.sendMessage(sendMessageDto);
    }
}